package com.benyanyi.okhttp.type;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * @author BenYanYi
 * @date 2019/01/30 22:38
 * @email ben@yanyi.red
 * @overview
 */
class SslConfig {
    /**
     * 生成安全套接字工厂，用于https请求的证书跳过
     * <p>
     * SSLSocketFactory ssfFactory = null;
     * try {
     * SSLContext sc = SSLContext.getInstance("TLS");
     * sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
     * ssfFactory = sc.getSocketFactory();
     * } catch (Exception e) {
     * }
     *
     * @return
     */
    static SSLSocketFactory createSSLSocketFactory() {

        SSLSocketFactory sslSocketFactory = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{getTrustManager()}, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sslSocketFactory;
    }

    static X509TrustManager getTrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }
}
